﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VoL.Domain.Infrastructure;
using VOL.Entity.DomainModels;
using VOL.WebApi.Common.DTO;
using VOL.WebApi.Common;
using VoL.Domain.IServices.BasicData;
using Microsoft.EntityFrameworkCore;
using Azure.Core;
using System.Threading;
using System.Transactions;

namespace VoL.Domain.Services.BasicData
{
    /// <summary>
    /// 病区病房配置命令处理器
    /// </summary>
    public partial class WardServices : IWardServices
    {
        /// <summary>
        /// 病房仓储接口
        /// </summary>
        private readonly IBaseRepository<Ward> _wardRepository;
        /// <summary>
        /// 病区病房配置仓储
        /// </summary>
        private readonly IBaseRepository<WardAreaHouse> _wardAreaHouseRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wardRepository">病房仓储接口</param>
        public WardServices(IBaseRepository<Ward> wardRepository, IBaseRepository<WardAreaHouse> wardAreaHouseRepository)
        {
            this._wardRepository = wardRepository;
            _wardAreaHouseRepository = wardAreaHouseRepository;
        }

        /// <summary>
        /// 病区病房配置命令处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public APIResult<List<WardAreaWardDTO>> WardAreaWardHouse(int wardAreaId)
        {
            // 获取该病区已关联的病房ID
            var assignedWardIds = _wardAreaHouseRepository.GetAll()
               .Where(wh => wh.WardAreaId == wardAreaId)
               .Select(wh => wh.WardId)
               .ToList();

            // 获取所有病房信息并区分已分配和未分配（假设Ward实体有Id和WardName属性）
            var allWards = _wardRepository.GetAll()
               .Select(w => new WardAreaWardDTO
               {
                   WardId = w.Id.ToString(),
                   WardName = w.WardName,
                   IsAssigned = assignedWardIds.Contains(w.Id)
               })
               .ToList();
            APIResult<List<WardAreaWardDTO>> res = new APIResult<List<WardAreaWardDTO>>()
            {
                Data = allWards,
                Code = APIEnum.查询成功,
                Message = APIEnum.查询成功.ToString()
            };
            return res;
        }


        // 定义常量
        private const string SUCCESS_MESSAGE = "病区病房配置保存成功";
        private const string FAILURE_MESSAGE = "保存失败：{0}";
        private const string SYSTEM_ERROR_MESSAGE = "系统错误：{0}";

        /// <summary>
        /// 添加病区病房配置
        /// </summary>
        /// <returns>返回数据</returns>
        public async Task<APIResult<object>> SaveWardServices(int wardAreaId, string wardIds)
        {
            APIResult<object> res = new APIResult<object>()
            {
                Message = APIEnum.创建成功.ToString(),
                Code = APIEnum.创建成功,
                Data = 1
            };
            try
            {
                // 检查病区下是否已有病房关联
                var existingWards = await _wardAreaHouseRepository
                   .FindAsync(x => x.WardAreaId == wardAreaId);

                using (TransactionScope transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        // 如果已有关联，先删除当前病区下的所有病房关联
                        if (existingWards.Any())
                        {
                            await _wardAreaHouseRepository.DeleteRang(existingWards);
                        }
                        int i = 0;
                        // 批量添加新的病房关联
                        if (!string.IsNullOrEmpty(wardIds))
                        {
                            var wardIdList = wardIds.Split(',').Select(int.Parse).ToList();
                            var newAssociations = wardIdList
                               .Select(wardId => new WardAreaHouse
                               {
                                   WardAreaId = wardAreaId,
                                   WardId = wardId
                               })
                               .ToList();
                            i = await _wardAreaHouseRepository.CreateRange(newAssociations, null);
                        }
                        if (i < 0)
                        {
                            res.Message = SUCCESS_MESSAGE;
                            res.Data = 1;
                        }
                        else
                        {
                            // 提交事务
                            transaction.Complete();
                        }
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务
                        res.Message = string.Format(FAILURE_MESSAGE, ex.Message);
                        res.Data = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                res.Message = string.Format(SYSTEM_ERROR_MESSAGE, ex.Message);
                res.Data = 0;
            }
            return res;
        }

    }
}
